
import { getUserInfoAPI, loginAPI } from '@/api/user'
import router, { constantRoutes, resetRouter } from '@/router'
import { getToken, setToken, removeToken } from '@/utils/auth'
import { Message } from 'element-ui'

export default {
  namespaced: true,
  state() {
    return {
      token: getToken(),
      userinfo: {},
      avatar: '',
      name: '',
      routes: constantRoutes,
      company: '',
      departmentName: ''
    }
  },
  mutations: {
    SET_TOKEN(state, token) {
      state.token = token
      setToken(token)
    },
    REMOVE_TOKEN(state) {
      removeToken()
      state.token = null
    },
    SET_USERINFO(state, userinfo) {
      state.userinfo = userinfo
      state.avatar = userinfo.staffPhoto
      state.name = userinfo.username
      state.company = userinfo.company
      state.departmentName = userinfo.departmentName
    },
    CLEAR_USERINFO(state) {
      state.userinfo = {}
    },
    SET_ROUTES(state, newRoutes) {
      state.routes = [...constantRoutes, ...newRoutes]
    }
  },
  actions: {
    async login(ctx, { mobile, password }) {
      const token = await loginAPI({ mobile, password })
      ctx.commit('SET_TOKEN', token)
      Message.success('登录成功')
      router.replace('/')
    },
    async logout(ctx) {
      ctx.commit('REMOVE_TOKEN')
      ctx.commit('CLEAR_USERINFO')
      resetRouter()
    },
    async getUserInfo(ctx) {
      const userinfo = await getUserInfoAPI()
      console.log(userinfo)

      ctx.commit('SET_USERINFO', userinfo)
      return userinfo
    }

  }
}

